package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.jwt.utils.AppJwtUtil;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
@Transactional
public class UserLoginServiceImpl extends BaseServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        //1.参数校验
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) return errorParam;
        AdUser one = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (one == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        String password = one.getPassword();//表中保存的密码
        String s = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());
        if (password.equals(s)) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(Long.valueOf(one.getId())));
            one.setPassword("");
            one.setSalt("");
            map.put("user", one);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "密码错误");
    }
}